﻿#region License

// // -------------------------------------------------------------------------------------
// // This information refers to LogAllEventsHandler.cs
// // 
// // Copyright 2012 ELEN7046 Group 2
// // 
// // Last Modified on: 2012-06-10
// // 
// // Contributors:
// // 
// // Amith Sewnarain
// // Elmar Vosloo
// // Jason Thorne
// // Satish Jewan
// // 
// // Wits University 
// // School of Electrical & Information Engineering
// // Software Engineering Tools and Techniques
// // 
// // -------------------------------------------------------------------------------------
// // 
// // This file (LogAllEventsHandler.cs) is part of the DishDash Event Visualization System.
// // 
// // DishDash is free software: you can redistribute it and/or modify
// // it under the terms of the GNU General Public License as published by
// // the Free Software Foundation, either version 3 of the License, or
// // (at your option) any later version.
// // 
// // DishDash is distributed in the hope that it will be useful,
// // but WITHOUT ANY WARRANTY; without even the implied warranty of
// // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// // GNU General Public License for more details.
// // 
// // You should have received a copy of the GNU General Public License
// // along with DishDash.  
// // If not, see <http://www.gnu.org/licenses/>.
// // -------------------------------------------------------------------------------------

#endregion

#region Using Directives

using DishDash.Common;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

#endregion

namespace LogAllEventsHandler
{
    public class LogAllEventsHandler
    {
        private readonly MongoCollection<PerformanceEvent> collection = null;
        private readonly MongoDatabase database = null;
        private readonly MongoServer server = null;

        /// <summary>
        /// Initializes a new instance of the <see cref="LogAllEventsHandler"/> class.
        /// </summary>
        public LogAllEventsHandler()
        {
            server = MongoServer.Create();
            database = server.GetDatabase("LogStore");
            collection = database.GetCollection<PerformanceEvent>("PerformanceEvents");
        }

        /// <summary>
        /// Logs the specified performance event.
        /// </summary>
        /// <param name="performanceEvent">The performance event.</param>
        public void Log(PerformanceEvent performanceEvent)
        {
            collection.Insert(performanceEvent);

            var zeroQuery = Query.EQ("_id", "0");

            var update = Update.AddToSet("categoryValues", performanceEvent.Category);

            collection.Update(zeroQuery, update, UpdateFlags.Upsert);
        }
    }
}